<template>
  <auth-page>
    <view class="coupon-details">
      <nav-bar
        :title="prototype.couponName"
        :bgColor="theme"
        :titleColor="colorTitle"
        showBorder
        :borderColor="theme"
      />
      <view class="detail-container" :style="{ backgroundColor: theme }">
        <!-- 有封面图片 -->
        <view class="cupon-detail-img" v-if="prototype.detailPage || type == 2">
          <!-- 为券的时候 -->
          <view v-if="type == 1">
            <view class="diy-bg">
              <xh-img v-if="prototype.detailPage" :src="prototype.detailPage" />
            </view>
          </view>
          <view
            class="circle circle-left"
            :style="{ background: theme }"
          ></view>
          <view
            class="circle circle-right"
            :style="{ background: theme }"
          ></view>
        </view>
        <!-- 没有封面图标 -->
        <view class="business-msg flex-x-0-center" v-else>
          <view class="business-msg-img">
            <xh-img v-if="prototype.logo" :src="prototype.logo"></xh-img>
            <xh-img v-else :src="couponMsg.pubDomainBusinessLogo"></xh-img>
          </view>
          <view class="store-name" v-if="prototype.brandName">{{
            prototype.brandName
          }}</view>
          <view class="store-name" v-else>{{
            couponMsg.pubDomainBusinessName
          }}</view>
          <view
            class="circle circle-left"
            :style="{ background: theme }"
          ></view>
          <view
            class="circle circle-right"
            :style="{ background: theme }"
          ></view>
        </view>
        <view class="detail-msg flex-y-center" v-if="!showDetail">
          <!-- 券类型，cash代金券，discount折扣券，exchange兑换券 -->
          <view
            v-if="
              prototype.couponType === 'cash' ||
              prototype.couponType === 'cash_wx_busi' ||
              prototype.couponType === 'cash_wx_pay'
            "
            class="flex-y-center"
          >
            <view class="coupon-title">
              满{{ prototype.transactionMinimum / 100 }} 立减{{
                prototype.denomination / 100
              }}
            </view>
          </view>
          <view
            v-else-if="
              prototype.couponType === 'discount' ||
              prototype.couponType === 'discount_wx_busi'
            "
          >
            <view class="coupon-title">
              满{{ prototype.transactionMinimum / 100 }} 立享{{
                prototype.discountPercent / 10
              }}折
            </view>
          </view>
          <view
            v-else-if="prototype.couponType === 'exchange'"
            class="flex-y-center"
          >
            <view class="coupon-title" v-if="prototype.denomination / 100">
              价值:{{ prototype.denomination / 100 }}元
            </view>
            <view class="conversion-describe"
              >兑换的内容:{{ prototype.exchangeThings }}</view
            >
          </view>
          <!-- 显示券码 -->
          <view class="code-container flex-y-center">
            <!-- 条码显示，1：条形码，2：二维码，3：二者 -->
            <!-- <image src="{{'data:image/png;base64,'+ qrCode}}" class="qr-code-big"></image> -->
            <image
              class="ean-code"
              @click="enlargeFenc({ type: 1, src: eanCode })"
              :src="'data:image/png;base64,' + eanCode"
              v-if="prototype.scanCode === 1 || prototype.scanCode === 3"
            ></image>
            <!-- 显示券码数字 -->
            <view
              class="flex-x-center-center coupon-code"
              v-if="type == 1 && couponCode"
            >
              {{ couponCode }}
            </view>
            <image
              class="qr-code"
              @click="enlargeFenc({ type: 2, src: qrCode })"
              :src="'data:image/png;base64,' + qrCode"
              v-if="prototype.scanCode === 2 || prototype.scanCode === 3"
            ></image>
          </view>
          <!-- 有效期 -->
          <view class="period-validity" v-if="effectiveTime && expireTime">
            {{ effectiveTime }} 到 {{ expireTime }}
          </view>
          <view v-else-if="prototype.endTime"
            >有效期至{{ prototype.endTime }}</view
          >
          <!-- 功能 -->
          <!--  -->

          <view
            v-if="prototype.functionButton"
            @click="handleButton"
            class="function-button flex-x-center-center"
            :style="{ background: theme, color: colorTitle }"
          >
            {{ functionButtonConfig.word }}
          </view>
        </view>
        <view
          class="flex-y-center upglide-view"
          v-if="!showDetail"
          @click="showDetailFunc"
        >
          <xh-img
            src="/wxapp/static/coupon/icon_up_white.png"
            v-if="colorTitle == '#ffffff'"
            width="42rpx"
            height="42rpx"
          ></xh-img>
          <xh-img
            src="/wxapp/static/coupon/icon_up_black.png"
            v-else-if="colorTitle == '#000000'"
            width="42rpx"
            height="42rpx"
          ></xh-img>
          <view
            class="upglide"
            :style="{ color: colorTitle == '#ffffff' ? '#fff' : '#000000' }"
          >
            点击查看详情
          </view>
        </view>
        <!-- 券详情 -->
        <view v-if="showDetail" class="coupon-detail flex-y">
          <view
            class="flex-y-center downglide-view"
            v-if="couponStatus === 1 && model === 1"
            @click="hiddenDetailFunc"
          >
            <!-- <view class="store-img iconfont "></view> -->
            <view class="downglide">点击查看二维码</view>
          </view>
          <!-- 券已核销  卡已用完 -->
          <view class="applied" v-if="couponStatus === 2">
            <view v-if="type == 1" class="flex-y-center">
              <view style="width:147rpx,height:87rpx">
                <xh-img src="/wxapp/static/coupon/pic_heixao.png"></xh-img
              ></view>
              <view style="margin-top: 10rpx">
                你的优惠券已经在{{ verifyMerchant }}的{{ verifyShop }}被核销
              </view>
            </view>
            <view v-else-if="type == 2" class="flex-y-center">
              <view style="width:147rpx,height:87rpx">
                <xh-img src="/wxapp/static/coupon/pic_cika.png"></xh-img
              ></view>
              <view
                style="margin-top: 10rpx"
                v-if="prototype.cardType == 'gift'"
              >
                您的卡已用当日可用金额
              </view>
              <view style="margin-top: 10rpx" v-else>您的卡已用完所有次数</view>
            </view>
          </view>
          <!-- 已过期 -->
          <view class="applied" v-else-if="couponStatus === 3">
            <view v-if="type == 1" class="flex-y-center">
              <view style="width:147rpx,height:87rpx">
                <xh-img src="/wxapp/static/coupon/pic_guoqi.png"></xh-img
              ></view>
              <view style="margin-top: 10rpx">您的优惠券已过期</view>
            </view>
            <view v-else-if="type == 2" class="flex-y-center">
              <view style="width:147rpx,height:87rpx">
                <xh-img src="/wxapp/static/coupon/pic_guoqi_card.png"></xh-img
              ></view>

              <view style="margin-top: 10rpx">您的卡已经过期</view>
            </view>
          </view>
          <!-- model为2的时候 -->
          <view
            v-if="model === 2"
            class="flex-y-center"
            style="margin-top: 28rpx"
          >
            <view v-if="prototype.status == 2" class="flex-y-center">
              <view
                v-if="
                  prototype.couponType === 'cash' ||
                  prototype.couponType === 'cash_wx_busi' ||
                  prototype.couponType === 'cash_wx_pay'
                "
                class="flex-y-center"
              >
                <view class="coupon-title">
                  满{{ prototype.transactionMinimum / 100 }}元 立减{{
                    prototype.denomination / 100
                  }}元
                </view>
              </view>
              <view
                v-else-if="
                  prototype.couponType === 'discount' ||
                  prototype.couponType === 'discount_wx_busi'
                "
              >
                <view class="coupon-title">
                  满{{ prototype.transactionMinimum / 100 }}元 立享{{
                    prototype.discountPercent / 10
                  }}折
                </view>
              </view>
              <view class="validity-date"
                >有效期至 {{ prototype.endTime }}</view
              >
              <!-- 扫码进来显示立即领取按钮 -->
              <button
                @click="handleMixinAuth(receiveBizCouponNewFunc)"
                class="no-get flex-x-center-center"
                :style="{ color: themem, borderColor: theme }"
              >
                立即领取
              </button>
            </view>
            <!-- 优惠券发放被暂停 -->
            <view
              v-else-if="prototype.status == 3"
              class="flex-y-center applied"
            >
              <xh-img
                src="/wxapp/static/coupon/pic_zanting.png"
                width="147rpx"
                height="87rpx"
              ></xh-img>
              <view class="zanting"
                >该优惠券暂时不可领取，你可以稍后再来看看</view
              >
            </view>
            <view class="flex-y-center applied" v-else>
              <xh-img
                src="/wxapp/static/coupon/pic_stop.png"
                width="147rpx"
                height="87rpx"
              ></xh-img>
              <view class="zanting">该优惠券领取活动已停止</view>
            </view>
          </view>
          <view class="detail-store-msg flex-x-center-center">
            <view class="detail-store-msg-img" v-if="prototype.logo">
              <xh-img :src="prototype.logo"></xh-img>
            </view>
            <view class="detail-store-msg-img" v-else>
              <xh-img :src="couponMsg.pubDomainBusinessLogo"></xh-img>
            </view>

            <view class="store-name" v-if="prototype.brandName">
              {{ prototype.brandName }}
            </view>
            <view class="store-name" v-else>{{
              couponMsg.pubDomainBusinessName
            }}</view>
          </view>
          <view class="coupon-msg">
            <view v-if="type == 1">
              <view
                class="flex-x-0-center coupon-msg-item"
                v-if="couponCode !== null"
              >
                <view class="field-name">券码</view>
                <view class="field-value">
                  {{ couponCode }}
                </view>
              </view>
              <view class="flex-x-0-center coupon-msg-item">
                <view class="field-name">券类型</view>
                <view
                  class="field-value"
                  v-if="
                    prototype.couponType === 'cash' ||
                    prototype.couponType === 'cash_wx_busi' ||
                    prototype.couponType === 'cash_wx_pay'
                  "
                >
                  代金券
                </view>
                <view
                  class="field-value"
                  v-else-if="
                    prototype.couponType === 'discount' ||
                    prototype.couponType === 'discount_wx_busi'
                  "
                >
                  折扣券
                </view>
                <view
                  class="field-value"
                  v-else-if="prototype.couponType === 'exchange'"
                >
                  兑换券
                </view>
              </view>
              <view
                class="flex-x-0-center coupon-msg-item"
                style="margin-bottom: 30rpx"
              >
                <view class="field-name">券名称</view>
                <view class="field-value">{{ prototype.couponName }}</view>
              </view>
              <view
                class="flex-x-0-center coupon-msg-item"
                v-if="
                  prototype.couponType === 'exchange' && prototype.denomination
                "
                style="margin-bottom: 30rpx"
              >
                <view class="field-name">价值</view>
                <view class="field-value"
                  >{{ prototype.denomination / 100 }}元</view
                >
              </view>
              <view
                class="flex-x-0-center coupon-msg-item"
                style="margin-bottom: 30rpx"
                v-if="
                  prototype.couponType === 'cash' ||
                  prototype.couponType === 'cash_wx_busi' ||
                  prototype.couponType === 'cash_wx_pay'
                "
              >
                <view class="field-name">券面额</view>
                <view class="field-value"
                  >{{ prototype.denomination / 100 }}元</view
                >
              </view>
              <view
                class="flex-x-0-center coupon-msg-item"
                style="margin-bottom: 30rpx"
                v-if="prototype.couponType != 'exchange'"
              >
                <view class="field-name">门槛</view>
                <view class="field-value">
                  满{{ prototype.transactionMinimum / 100 }}元可用,最多可叠加{{
                    prototype.maxUseNum
                  }}张
                </view>
              </view>
            </view>
            <view class="flex-x-0-center coupon-msg-item">
              <view class="field-name">可用时间</view>
              <view class="field-value" style="flex-wrap: wrap">
                <view>{{ couponInstructionArr.returnString }}</view>
                <block
                  v-for="item in couponInstructionArr.timeString"
                  :key="item"
                >
                  <view>{{ item }}</view>
                </block>
              </view>
            </view>
            <view
              class="flex-x-0-center coupon-msg-item"
              v-if="
                availableTime.timeType === 1 &&
                includesType.includes(prototype.couponType, type) &&
                model == 2
              "
            >
              <view class="field-name">生效时间</view>
              <view class="field-value" v-if="prototype.secondDayAvailable">
                领取后第二天生效
              </view>
              <view class="field-value" v-else>领取后立即生效</view>
            </view>
            <view
              class="flex-x-0-center coupon-msg-item"
              v-if="prototype.description"
            >
              <view class="field-name">使用说明</view>
              <view class="field-value">{{ prototype.description }}</view>
            </view>
            <view
              class="flex-x-0-center coupon-msg-item"
              @click="toAllShopAvailable"
              v-if="prototype.couponType != 'cash_wx_pay'"
            >
              <view class="field-name">适用范围</view>
              <view
                class="field-value flex-x-between-center flex-1"
                style="padding-right: 16rpx"
              >
                <view v-if="prototype.verifyMerchant == 1">本商户所有店铺</view>
                <view v-if="prototype.verifyMerchant == 2"
                  >本商户及所有合作商户所有店铺</view
                >
                <view v-if="prototype.verifyMerchant == 3"
                  >本商户及部分合作商户店铺</view
                >
                <view v-if="prototype.verifyMerchant == 4">本商户部分店铺</view>
                <view class="iconfont icon-xiangyoujiantou"> </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <enlarge-image ref="enlargeImage" />
      <shop-list-dialog
        :visible.sync="showShopList"
        :couponCode="prototype.id"
      />
    </view>
  </auth-page>
</template>

<script>
import {
  getCouponDetail,
  getPrototypeInfo,
  receiveCoupon,
} from "@/service/api/sp-coupon/index";
import enlargeImage from "@/pages/sp-coupon/pages/coupon-detail/components/enlargeImage/index.vue";
import shopListDialog from "@/pages/sp-coupon/pages/coupon-detail/components/shopListDialog/index.vue";
import { mixinAuth } from "@/mixin/sp-common/mixin-auth";
import pageHandleUtil from "../../../../utils/pageHandleUtil";
import dayjs from "dayjs";
import $color from "./color";
import { mapState } from "vuex";

export default {
  mixins: [mixinAuth],
  components: {
    enlargeImage,
    shopListDialog,
  },
  watch: {
    app_token(value) {
      console.log(value)
      if(value){
        this.getDtail()
      }
    },
  },
  mounted() {
    this.getDtail();
  },
  computed: {
    ...mapState("sp-common/auth", ["isAnonUser", "app_token"]),
  },
  data() {
    return {
      navHeight: 80,
      couponStatus: null,
      couponDetail: null,
      //是否过期
      isExpired: false,
      qrNumber: "",
      pageBgColor: {},
      eanCode: "",
      qrCode: "",
      //使用时间
      couponInstructionArr: [],
      couponCode: null,
      //卡的code
      code: null,
      //起始时间
      effectiveTime: null,
      //结束时间
      expireTime: null,
      //券原型
      prototype: {},
      touchX: 0,
      touchY: 0,
      showDetail: false,
      //按钮配置信息
      functionButtonConfig: null,
      //券状态，1：正常，2：已使用，3：已过期，4：已锁定
      status: 1,
      interTime: null,
      // 1.券 2.卡
      type: 1,
      //1 详情页  2.扫码领取页
      model: 1,
      loading: true,
      //核销商户
      verifyMerchant: "",
      //核销门店
      verifyShop: "奶茶店",
      //扫码领取页面展示信息的code
      receiveCode: "",
      //轮询的定时器
      setIntervalResult: null,
      //券的主题色
      theme: null,
      //券的字体颜色
      colorTitle: null,
      height: 0,
      availableTime: null,
      couponMsg: "",
      showShopList: false,
    };
  },
  methods: {
    getCouponDetail() {
      let { couponCode } = this;
      getCouponDetail({ couponCode }).then((res) => {
        this.couponMsg = res;
        let {
          status,
          availableTime,
          eanCode,
          qrCode,
          prototype,
          effectiveTime,
          expireTime,
        } = res;
        // 时段可使用渲染
        let couponInstructionArr = {};
        //1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用，5：全时段可用
        if (availableTime && availableTime.timeType != 5) {
          if (availableTime.timeType == 1) {
            //领券后N天可用
            couponInstructionArr = {
              returnString: "领券后" + availableTime.days + "天可用",
              timeString: [],
            };
          } else if (availableTime.timeType == 2) {
            //规则星期可用
            couponInstructionArr = pageHandleUtil.dillCouponWeek(
              [],
              false,
              availableTime
            );
          } else if (availableTime.timeType == 3) {
            //规则日期可用
            couponInstructionArr = pageHandleUtil.dillCouponDay(
              [],
              false,
              availableTime
            );
          } else if (availableTime.timeType == 4) {
            //不规则日期可用
            let timeString = pageHandleUtil.mToStrArray(availableTime);
            // let returnString = availableTime.dateList.replace(/:/g, " ~ ");
            let returnString = "";
            let dateString = availableTime.dateList
              .replace(/:/g, " ~ ")
              .split(",");
            timeString = dateString.concat(timeString);
            couponInstructionArr = {
              returnString: returnString,
              timeString: timeString,
            };
          }
        } else {
          couponInstructionArr = {
            returnString: `全部时段可用`,
            timeString: ``,
          };
        }
        if (status !== 1) {
          this.showDetail = true;
        } else {
          this.showDetail = false;
          // if (this.setIntervalResult) {
          //   console.log("释放定时器")
          //   clearInterval(this.setIntervalResult);
          //   this.setData({ setIntervalResult: null })
          // }
        }
        if (status === 5 && !this.setIntervalResult) {
          // let setIntervalResult = setInterval(() => {
          //   return this.couponDetailReq();
          // }, 1000);
          // this.setData({ setIntervalResult })
        }
        this.couponInstructionArr = couponInstructionArr;
        this.couponStatus = status;
        this.effectiveTime = effectiveTime;
        this.expireTime = expireTime;
        this.eanCode = eanCode;
        this.qrCode = qrCode;
        this.loading = false;
        this.availableTime = availableTime;
        this.prototype = prototype;
        if (status === 2) {
          // this.couponStatusReq()
        }
        this.resetDescFunc();
        let theme, colorTitle;
        if (prototype.theme) {
          theme = prototype.theme;
          colorTitle = $color.getTitleColor(theme.toLowerCase());
        } else {
          theme = this.themeColor;
          colorTitle = this.themeTitleColor;
        }
        this.theme = theme;
        this.colorTitle = colorTitle;
        wx.setBackgroundColor({
          backgroundColorTop: theme,
          backgroundColorBottom: theme,
        });
        this.handleButtonConfig();
        this.handleTimeConfig();
      });
    },
    getPrototypeInfoFunc() {
      let { receiveCode } = this;
      getPrototypeInfo({ receiveCode }).then((res) => {
        let { availableTime, prototype } = res;
        // 时段可使用渲染
        let couponInstructionArr = {};
        //1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用，5：全时段可用
        if (availableTime && availableTime.timeType != 5) {
          //    if (availableTime.availablePeriod || availableTime.dateList) {
          console.log("availableTime.timeType", availableTime.timeType);
          if (availableTime.timeType == 1) {
            //领券后N天可用
            couponInstructionArr = {
              returnString: "领券后" + availableTime.days + "天可用",
              timeString: [],
            };
          } else if (availableTime.timeType == 2) {
            //规则星期可用
            couponInstructionArr = pageHandleUtil.dillCouponWeek(
              [],
              false,
              availableTime
            );
          } else if (availableTime.timeType == 3) {
            //规则日期可用
            console.log(
              "availableTime.timeType === 3",
              availableTime.timeType === 3
            );
            couponInstructionArr = pageHandleUtil.dillCouponDay(
              [],
              false,
              availableTime
            );
          } else if (availableTime.timeType == 4) {
            //不规则日期可用
            // couponInstructionArr = pageHandleUtil.dillCouponDay(availablePeriods);
            let timeString = pageHandleUtil.mToStrArray(availableTime);
            let returnString = availableTime.dateList.replace(/:/g, " ~ ");
            couponInstructionArr = {
              returnString: returnString,
              timeString: timeString,
            };
          }
          // }
        } else {
          couponInstructionArr = {
            returnString: `全部时段可用`,
            timeString: ``,
          };
        }
        this.couponInstructionArr = couponInstructionArr;
        this.prototype = prototype;
        this.availableTime = availableTime;
        this.showDetail = true;
        this.loading = false;
        let theme, colorTitle;
        if (prototype.theme) {
          theme = prototype.theme;
          colorTitle = $color.getTitleColor(theme.toLowerCase());
        } else {
          theme = this.data.themeColor;
          colorTitle = this.data.themeTitleColor;
        }
        (this.theme = theme), (this.colorTitle = colorTitle);
      });
    },
    //显示按钮
    handleButtonConfig() {
      let prototype = this.prototype;
      let functionButtonConfig;
      if (prototype.functionButton && prototype.functionButtonConfig) {
        functionButtonConfig = JSON.parse(prototype.functionButtonConfig);
      }
      this.functionButtonConfig = functionButtonConfig;
    },
    //显示时间
    handleTimeConfig() {
      let effectiveTime = this.effectiveTime;
      let expireTime = this.expireTime;
      if (effectiveTime) {
        effectiveTime = dayjs(effectiveTime).format("YYYY-MM-DD");
      }
      if (expireTime) {
        expireTime = dayjs(expireTime)
          .subtract(1, "second")
          .format("YYYY-MM-DD");
      }
      this.effectiveTime = effectiveTime;
      this.expireTime = expireTime;
    },
    handleButton() {
      let { appId, page } = this.functionButtonConfig;
      const accountInfo = wx.getAccountInfoSync();
      let nowAppId = accountInfo.miniProgram.appId;
      if (nowAppId === appId) {
        this.$myTool.jumpPage(page);
      } else {
        //非本小程序appid
        wx.navigateToMiniProgram({
          appId: appId,
          path: page,
        });
      }
    },
    //显示券详情
    showDetailFunc() {
      if (this.type == 1 && this.couponStatus == 1 && this.model == 1) {
        this.showDetail = true;
      }
    },
    //隐藏券详情
    hiddenDetailFunc() {
      if (this.type == 1 && this.couponStatus == 1 && this.model == 1) {
        this.showDetail = false;
      }
    },
    //组装券描述
    resetDescFunc() {
      let prototype = this.prototype;
      let desc = prototype.description;
      //如果是折扣券，组装优惠金额上限
      if (
        prototype.couponType === "discount" &&
        prototype.discountMaximum > 0
      ) {
        if (desc) {
          desc = desc + `,最多可优惠${prototype.discountMaximum / 100}元`;
        } else {
          desc = `最多可优惠${prototype.discountMaximum / 100}元`;
        }

        this.prototype.description = desc;
      }
    },
    enlargeFenc(obj) {
      let { src, type } = obj;
      if (!src) return;
      this.$refs.enlargeImage.dialogShow(src, type);
    },
    toAllShopAvailable() {
      this.showShopList = true;
    },
    receiveBizCouponNewFunc() {
      let {
        receiveCode
      } = this;
      receiveCoupon({ receiveCode }).then((res) => {
        if (res) {
          uni.showToast({
            title: "领取成功",
            icon: "success",
            duration: 2000,
          });
          this.model = 1;
          this.showDetail = false;
          this.couponCode = res;
          this.getCouponDetail();
        }
      });
    },
    getDtail() {
      if(!this.app_token) return
      if (this?.$Route?.query?.couponCode) {
        this.couponCode = this?.$Route?.query?.couponCode;
        this.type = 1;
        this.getCouponDetail();
      }
      if (this?.$Route?.query?.receiveCode) {
        (this.receiveCode = this?.$Route?.query?.receiveCode), (this.model = 2);
        this.getPrototypeInfoFunc();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/pages/sp-coupon/styles/couponDetail.scss";
</style>
